package io.renren.modules.wx.controller;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.R;
import io.renren.modules.util.WechatUtil;
import io.renren.modules.wx.dao.UserMapper;
import io.renren.modules.wx.entity.StudentEntity;
import io.renren.modules.wx.entity.User;
import io.renren.modules.wx.service.StudentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Api(tags = "微信登录接口")
@RestController
public class WxController {
    @Value("${wx.appid}")
    String appid;
    @Value("${wx.secret}")
    String secret ;

    @Autowired
    UserMapper userMapper;

    @Autowired
    StudentService studentService;


    @PostMapping("/wx/login")
    public R user_login(@RequestParam(value = "code") String code) {

        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(appid, secret, code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

//        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
//        if (!signature.equals(signature2)) {
//            return R.error().message("签名校验失败");
//        }

        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
        User user = userMapper.getByOpenId(openid);
        if (user == null) {
            StudentEntity student = new StudentEntity();
            student.setUsername("用户" + openid);
            studentService.save(student);
            user = new User(openid, student.getStudentId());
            userMapper.insert(user);
        }
        return R.ok().put("data", user);
    }

}
